package com.xizimall.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.net.ftp.FTPFile;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.xizimall.service.PictureService;
import com.xizimall.common.utils.FtpUtil;
import com.xizimall.common.utils.IDUtils;

/**
 * 图片上传服务
 * <p>Title: PictureServiceImpl</p>
 * <p>Description: </p>
 * <p>华南理工大学研究生</p> 
 * @author	李隆熹
 * @date	2018年4月14日下午5:18:40
 * @version 1.0
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private int FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;
	@Override
	public Map uploadPictrue(MultipartFile uploadFile){
		Map resultMap=new HashMap<>();
		// 生成新的文件名
		try {
			//取原始文件名
			String oldName=uploadFile.getOriginalFilename();
			//生成新文件名
			//UUID.randomUUID();
			String newName=IDUtils.genImageName();
			newName =newName+oldName.substring(oldName.lastIndexOf("."));
			//图片上传
			String imagePath=new DateTime().toString("/yyyy/MM/dd");
			boolean result=FtpUtil.uploadFile(FTP_ADDRESS,FTP_PORT,FTP_USERNAME, FTP_PASSWORD, 
		    FTP_BASE_PATH,imagePath , newName,uploadFile.getInputStream());
			if(!result){
				resultMap.put("error", 1);
				resultMap.put("message", "文件上传失败");
				}
			resultMap.put("error", 0);
			resultMap.put("url",IMAGE_BASE_URL+imagePath+"/"+newName);
			return resultMap;
		} catch (Exception e) {
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
			return resultMap;
		}
	}
 }
